/*
 * Copyright 2004-2005 公司名
 * 本软件及其所有拷贝的名称，与光盘上或本软件中注明的公司同在。
 * 本软件及文档享有版权，并受国家版权法及国际协约条款的保护。
 * 您不可以从本软件中去掉其版权声明；并保证为本软件的拷贝（本部或部分）* 复制版权声明。
 * 您同意制止以任何形式非法拷贝本软件及文档。
 * 版权信息参见：
 *      http://www.companyname.cn/licenses
 */

package com.companyname.common.util.mvc.valid.imp._timestamp;

import com.companyname.common.util.mvc.valid.AbstractValidator;
import com.companyname.common.util.mvc.valid.InitValidatorException;
import com.companyname.common.util.mvc.valid.InvalidParamException;

import java.util.Date;

import java.sql.Timestamp;

import java.text.SimpleDateFormat;
import java.text.ParseException;

import org.apache.log4j.Logger;

/**
 * timestamp格式 校验器 之 格式
 *
 * created by amon 2005-5-17 20:39
 */

public class IsTimestamp implements AbstractValidator
{
        static Logger logger = Logger.getLogger(IsTimestamp.class);

        public boolean validing(Object param,Object[] initValues)
          throws InitValidatorException
        {
                return (this.getParamTime(param,initValues) != null);
        }

        public Timestamp getParamTime(Object param,Object[] initValues)
          throws InitValidatorException
        {
                String par;
                if(initValues.length == 0)
                {
                        par = "yyyy-MM-dd HH:mm:ss";
                }
                else
                {
                        par = (String)initValues[0];
                }
                SimpleDateFormat sdf = new SimpleDateFormat(par);

                try
                {
                        logger.debug("1. 判断 " + (String)param + " 是不是　timestamp格式 ");
                        return new Timestamp((sdf.parse((String)param)).getTime()) ;
                }
                catch(ParseException iare)
                {
                        // 格式错误
                        logger.error("IsTimestamp(" + par + ")异常:" +  iare.toString());
                        return null;
                }
                catch(ClassCastException cce)
                {
                        throw new InitValidatorException("参数传递异常：" + this.help());
                }
        }

        public Timestamp now()
        {
                return new Timestamp((new Date()).getTime());
        }

        // 一个个取初始化值
        private Timestamp initValue2Timestamp(Object initValue)
          throws InitValidatorException,
                 ClassCastException
        {
                try
                {
                        if(((String)initValue).equalsIgnoreCase("${now}"))
                        {
                                return this.now();
                        }
                        else
                        {
                                return Timestamp.valueOf((String)initValue);
                        }
                }
                catch(IllegalArgumentException iae)
                {
                        throw new InitValidatorException("校验参数日期格式错误: '" + initValue + "' 应为'yyyy-mm-dd hh:mm:ss' 或 '${now}'");
                }
        }

        // 取得被比较值
        public Timestamp getInitValue(Object[] initValues)
          throws InitValidatorException
        {
                try
                {
                        logger.debug(" 数据类型校验 -- initValues");
                        Timestamp equalValue = null;
                        if(initValues.length == 1)
                        {
                                return this.initValue2Timestamp(initValues[0]);
                        }
                        if(initValues.length == 2)
                        {
                                SimpleDateFormat sdf = new SimpleDateFormat((String)initValues[0]);
                                try
                                {
                                        return new Timestamp((sdf.parse((String)initValues[1])).getTime());
                                }
                                catch(ParseException iare)
                                {
                                        // 格式错误
                                        throw new InitValidatorException("校验参数日期格式错误: '" + initValues[0] + "' 无法根据'" + initValues[1] + "'格式进行转换");
                                }
                        }
                        if(initValues.length == 3)
                        {
                                Timestamp t1 = this.initValue2Timestamp(initValues[0]);
                                String t2 = (String)initValues[1];
                                String operator = (String)initValues[2];
                                return this.operate(t1,t2,operator);
                        }
                        throw new InitValidatorException("配置参数传递异常：" + this.help());
                }
                catch(IllegalArgumentException iare)
                {
                        // 格式错误
                        logger.error("IsTimestamp异常:" + iare.toString());
                        throw new InitValidatorException("IsTimestamp异常:" + iare.toString());
                }
                catch(ClassCastException cce)
                {
                        throw new InitValidatorException("<param>参数传递异常");
                }
        }

        // 参数运算
        private Timestamp operate(Timestamp t1,String t2,String operator)
          throws InitValidatorException
        {
                String[] ymdhmsf = t2.split("\\.")[0].split(" ");
                String[] ymd = ymdhmsf[0].split("-");
                String[] hmsf = ymdhmsf[1].split(":");
                int y = Integer.parseInt(ymd[0]);
                int m = Integer.parseInt(ymd[1]);
                int d = Integer.parseInt(ymd[2]);
                int h = Integer.parseInt(hmsf[0]);
                int mi = Integer.parseInt(hmsf[1]);
                int s = Integer.parseInt(hmsf[2]);
                Timestamp tempTime = new Timestamp(t1.getTime());
                if(operator.equals("+"))
                {
                        tempTime.setYear(tempTime.getYear() + y);
                        tempTime.setMonth(tempTime.getMonth() + m);
                        tempTime.setDate(tempTime.getDate() + d);
                        tempTime.setHours(tempTime.getHours() + h);
                        tempTime.setMinutes(tempTime.getMinutes() + mi);
                        tempTime.setSeconds(tempTime.getSeconds() + s);
                        return tempTime;
                }
                if(operator.equals("-"))
                {
                        tempTime.setYear(tempTime.getYear() - y);
                        tempTime.setMonth(tempTime.getMonth() - m);
                        tempTime.setDate(tempTime.getDate() - d);
                        tempTime.setHours(tempTime.getHours() - h);
                        tempTime.setMinutes(tempTime.getMinutes() - mi);
                        tempTime.setSeconds(tempTime.getSeconds() - s);
                        return tempTime;
                }
                throw new InitValidatorException("配置参数传递异常：暂时不支持 '" + operator + "'"+ this.help());

        }

        public String help()
        {
               return "((String:'yyyy-mm-dd hh:mm:ss')param  , Object[0]: (String)equalValue  ) " +
                      " or ((String:'yyyy-mm-dd hh:mm:ss')param  , Object[0]: param.from param.key  Object[1]: (String)operatedValue Object[2]: (String)'+'|'-' )";
        }
}
